package com.example.bookkeepingelf.base.utils;

import android.util.Log;

import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.bean.BeanUtil;

/**
 * 异步工具类
 */
public class AsyncUtils {

    /**
     * 单线程池
     */
    private static ExecutorService executorService = Executors.newSingleThreadExecutor();

    /**
     * 私有构造方法，防止实例化
     */
    private AsyncUtils() {}

    /**
     * 单线程池
     * @param runnable 需要执行的任务
     */
    public static void runSingle(Runnable runnable) {
        if (Objects.isNull(runnable)) {
            throw new RuntimeException("runnable is null");
        }
        // 检查线程池是否已关闭或已终止
        if (executorService.isShutdown() || executorService.isTerminated()) {
            System.out.println("线程池已关闭，重新初始化线程池");
            // 重新初始化线程池
            AsyncUtils.reinitialize();
        }
        try {
            executorService.execute(() -> {
                Log.i("com.example.bookkeepingelf.base.utils.runSingle",String.format(" 异步任务开始执行，线程名称【%s】" , Thread.currentThread().getName()));
                try {
                    runnable.run();
                } catch (Exception e) {
                    System.out.println("runSingle异步任务执行出错: " + e.getMessage());
                    Log.e("com.example.bookkeepingelf.base.utils.runSingle"," 异步任务执行出错: ", e);
                }
                Log.i("com.example.bookkeepingelf.base.utils.runSingle",String.format(" 异步任务执行完毕，线程名称【%s】" , Thread.currentThread().getName()));
            });
        } catch (Exception e) {
            Log.e("com.example.bookkeepingelf.base.utils.runSingle"," 提交任务失败: ", e);
        }
    }

    /**
     * 单线程池
     * @param runnable 需要执行的任务
     * @param isShutdown 是否关闭线程池
     */
    public static void runSingle(Runnable runnable, boolean isShutdown) {
        AsyncUtils.runSingle(runnable);
        // 如果需要关闭线程池
        if (isShutdown) {
            AsyncUtils.shutdownSingle();
        }
    }

    /**
     * 关闭线程池
     */
    public static void shutdownSingle() {
        executorService.shutdown();
        try {
            if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            executorService.shutdownNow();
        }
        Log.i("com.example.bookkeepingelf.base.utils.shutdownSingle"," 异步任务执行完毕，已关闭");
    }

    /**
     * 重新初始化线程池
     */
    private static void reinitialize() {
        executorService = Executors.newSingleThreadExecutor();
        Log.i("com.example.bookkeepingelf.base.utils.reinitialize"," 线程池已重新初始化");

    }

}